package com.fanjia.taobao.security.filter;


import com.fanjia.taobao.common.util.ResEntity;
import com.fanjia.taobao.user.entity.User;
import com.fanjia.taobao.common.util.JwtTokenProvider;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author codermy
 * @createTime 2020/7/20
 */
//1。。。。。每次请求通过的拦截器。
@Component
public class VerifyTokenFilter extends OncePerRequestFilter {

    @Autowired
    JwtTokenProvider tokenProvider;
    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token != null && tokenProvider.validateToken(token)) {
            String username = Jwts.parser().setSigningKey(tokenProvider.getSecret()).parseClaimsJws(token).getBody().getSubject();
            System.out.println("==============="+username);
            User userDetails =(User) userDetailsService.loadUserByUsername(username);
            Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        super.doFilter(request, response ,chain);
    }



}
